#include "../../framework/framework.h"
#include "../inc/xDevice.h"
#include "../inc/xWindow.h"
#include "../inc/xD3DEnv.h"
namespace Sky
{

TResult Sky::xDevice::onCreate(xDxApp* app )
{
	TResult hr;
	if(app == vNull){
		myTrace0A(M,"onCreate() app == vNull");
		return XE_ARGUMENT;
	} // if(app == vNull)
	m_PresentParams.hDeviceWindow = app->getWindow()->getHWnd();
	if(m_PresentParams.hDeviceWindow == vNull)
		return XE_ARGUMENT;
	if(app->getD3DEnv() == vNull){
		myTrace0A(M,"app->getD3DEnv() == vNull");
		return XE_ARGUMENT;
	}
	hr = app->getD3DEnv()->getDirect3D9()->CreateDevice(m_AdapterOrdinal,m_DeviceType,m_PresentParams.hDeviceWindow,m_BehaviorFlags,&m_PresentParams,(LPDIRECT3DDEVICE9*)getResAddr());
	if(FAILED(hr))
	{
		myDx_Trace_hr0(M,hr,_XT("CreateDevice() failed"));
		return XE_APICALL;
	}
	return XE_OK;
}
TResult Sky::xDevice::onDelete( xDxApp* app )
{	
	SAFE_RELEASE(m_Res);
	return XE_OK;
}

Sky::xDevice::xDevice()
{
	Initialise();
}

xDevice::~xDevice()
{
	Finalise();
}

TVoid xDevice::Finalise()
{
	SAFE_RELEASE(m_Res);
}

TVoid xDevice::Initialise()
{
	m_Res = vNull;
	m_AdapterOrdinal = D3DADAPTER_DEFAULT;
	m_DeviceType = D3DDEVTYPE_HAL;
	m_BehaviorFlags = D3DCREATE_PUREDEVICE | D3DCREATE_HARDWARE_VERTEXPROCESSING;
	m_AdapterFormat = D3DFMT_A8R8G8B8;
	m_PresentParams.BackBufferWidth = 1024;
	m_PresentParams.BackBufferHeight = 768;
	m_PresentParams.BackBufferCount = 1;
	m_PresentParams.BackBufferFormat =  D3DFMT_A8R8G8B8;
	m_PresentParams.AutoDepthStencilFormat = D3DFMT_D24S8;
	m_PresentParams.EnableAutoDepthStencil = vTrue;

	m_PresentParams.MultiSampleQuality = 1;
	m_PresentParams.MultiSampleType = D3DMULTISAMPLE_4_SAMPLES;
	m_PresentParams.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
	m_PresentParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
	m_PresentParams.Windowed = vTrue;
	m_PresentParams.Flags = 0;
	m_PresentParams.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
}

TInt xDevice::Release()
{
	TInt cnt = getDevice9()->Release();
	m_Res = vNull;
	return cnt;
}

TResult xDevice::Reset()
{
	TResult hr = getDevice9()->Reset(&m_PresentParams);
	if(FAILED(hr))
		return XE_APICALL;
	return XE_OK;
}

LPDIRECT3DDEVICE9 xDevice::getDevice9()
{
	return m_Res;
}
}